/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.barrientosjunior.massfilerenamer.parser;

import br.com.barrientosjunior.massfilerenamer.parser.element.Element;
import br.com.barrientosjunior.massfilerenamer.parser.element.ExtensionTagElement;
import br.com.barrientosjunior.massfilerenamer.parser.element.StringElement;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Junior
 */
public class PatternParser {

    private int i = 0;

    public void setI(int i){
        this.i = i;
    }

    /**
     * Pareses the String and create an list with its correspondents tag commands.
     * @param pattern
     * @return
     * @throws Exception
     */
    public List parse(String pattern) throws Exception{
        ArrayList<Element> formattedPattern = new ArrayList<Element>();

        try {
            int startChar = -1;        

            for (i = 0; i < pattern.length() ; i++) {
                char c = pattern.charAt(i);
                switch(c){
                    case '[':
                        
                        if (startChar >= 0){

                            formattedPattern.add(new StringElement(pattern.substring(startChar, i)));
                            startChar = -1;
                            
                        }
                        if (pattern.substring(i, i + 5).equalsIgnoreCase("[name")) {

                            NameTagParser parser = new NameTagParser();
                            formattedPattern.add(parser.parse(this,pattern,i));

                        } else if (pattern.substring(i, i + 5).equalsIgnoreCase("[cont")) {

                            ContTagParser parser = new ContTagParser();
                            formattedPattern.add(parser.parse(this,pattern,i));
                            
                        }
                        
                        break;

                    case '\\':
                        if ("[".equals(String.valueOf(pattern.charAt(i+1))))
                            i++;
                        break;
                        
                    default:
                        if (startChar < 0){
                            startChar = i;
                            break;
                        }
                }
            }
            formattedPattern.add(new ExtensionTagElement());
            
        } catch (IndexOutOfBoundsException e) {
            throw new Exception("Erro geral de parse");
        } catch (Exception e) {
            throw e;
        }

        return formattedPattern;
    }
    
}
